package com.ay.smartpark.sdk.controller;

import com.alibaba.fastjson.JSONArray;

import com.ay.smartpark.sdk.common.base.DownloadFileResponse;
import com.ay.smartpark.sdk.common.base.ResponseBean;
import com.ay.smartpark.sdk.common.base.UploadFileResponse;
import com.ay.smartpark.sdk.common.utils.CookieUtil;
import com.ay.smartpark.sdk.common.utils.UploadFileUtils;
import com.ay.smartpark.sdk.service.UploadAndDownloadFileService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Controller
@RequestMapping("/file")
public class UploadAndDownloadFileController {

    private static final Logger logger = LoggerFactory.getLogger(UploadAndDownloadFileController.class);

    @Autowired
    private UploadAndDownloadFileService uploadAndDownloadFileService;

    /**
     * 上传文件：
     * 1.通过平台上传接口上传文件到平台文件服务器，返回文件名并解密
     * 2.将解密后的文件名转化成Json格式保存数据库
     *
     * @param multipartFiles
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean uploadFiles(@RequestParam("files") MultipartFile[] multipartFiles, HttpServletRequest request) {
        if (multipartFiles == null || multipartFiles.length == 0) {
            return ResponseBean.fail("上传文件为空");
        }
        //Todo 默认网络协议，例：http://，如为空，使用default.properties中的配置
        String defaultWebProtocol = "";
        //Todo 默认网络域名，例：www.proj.chongqingjscy.aysaas.com:23113，如为空，使用default.properties中的配置
        String defaultWebDomain = "";
        //Todo 字段名，例：biaozhutupian
        String fieldName = "";
        //Todo 表名，不要拼接，例：shiti
        String tableName = "";
        //Todo sessionId
        String phpSessionId = CookieUtil.getValue(request, "PHPSESSID");
        //Todo 保存文件路径，下面是返回项目在容器中的实际发布运行的路径
        String tmpFilePath = request.getSession().getServletContext().getRealPath("/tmpFilePath");
        //通过平台上传文件
        UploadFileResponse uploadFileResponse;
        try {
            uploadFileResponse = uploadAndDownloadFileService.uploadFiles(defaultWebProtocol, defaultWebDomain, fieldName, tableName, phpSessionId, tmpFilePath, multipartFiles);
        } catch (Exception e) {
            return ResponseBean.fail(e.getMessage());
        }
        if (StringUtils.isNotBlank(uploadFileResponse.getError())) {
            List<String> resultList = uploadFileResponse.getData();
            JSONArray fuJianJsonArray = UploadFileUtils.getFuJianJsonArray(resultList);
            //Todo 以下进行保存fuJianJsonArray到数据库操作

            //返回成功结果
            return ResponseBean.success("success");
        } else {
            //返回失败结果
            return ResponseBean.fail(uploadFileResponse.getError());
        }
    }


    /**
     * 下载文件
     *
     * @param response
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    @ResponseBody
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
        //Todo 查询数据库中下载文件的信息

        //Todo 默认网络协议，例：http://，如为空，使用default.properties中的配置
        String defaultWebProtocol = "";
        //Todo 默认网络域名，例：www.proj.chongqingjscy.aysaas.com:23113，如为空，使用default.properties中的配置
        String defaultWebDomain = "";
        //Todo 该记录保存文件名
        String fileNameFromDB = "";
        //Todo 该记录id，即行id
        String recordId = "";
        //Todo 字段名，例：biaozhutupian
        String fieldName = "";
        //Todo 表名，不要拼接，例：shiti
        String tableName = "";
        //Todo sessionId
        String phpSessionId = CookieUtil.getValue(request, "PHPSESSID");

        DownloadFileResponse downloadFileResponse = null;
        try {
            downloadFileResponse = uploadAndDownloadFileService.downloadFile(defaultWebProtocol, defaultWebDomain, fileNameFromDB, recordId, fieldName, tableName, phpSessionId);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (StringUtils.isBlank(downloadFileResponse.getError())) {
            try {
                InputStream inputStream = downloadFileResponse.getInputStream();
                if (inputStream != null) {
                    //文件名根据实际文件名定义
                    String fileName = "file.docx";
                    String filePath = "/home/" + File.separator + fileName;
                    File file = new File(filePath);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    byte[] bs = new byte[1024];
                    int len = 0;
                    FileOutputStream out = new FileOutputStream(file);
                    while ((len = inputStream.read(bs)) != -1) {
                        out.write(bs, 0, len);
                    }
                    out.flush();
                    out.close();
                    inputStream.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        } else {
            logger.error(downloadFileResponse.getError());
        }
    }


    /**
     * 返回下载文件url
     *
     * @return
     */
    @RequestMapping(value = "/downloadFileUrl", method = RequestMethod.GET)
    @ResponseBody
    public String getDownloadFileUrl(HttpServletRequest request) {
        //Todo 查询数据库中下载文件的信息

        //Todo 默认网络协议，例：http://，如为空，使用default.properties中的配置
        String defaultWebProtocol = "";
        //Todo 默认网络域名，例：www.proj.chongqingjscy.aysaas.com:23113，如为空，使用default.properties中的配置
        String defaultWebDomain = "";
        //Todo 该记录保存文件名
        String fileNameFromDB = "";
        //Todo 该记录id，即行id
        String recordId = "";
        //Todo 字段名，例：biaozhutupian
        String fieldName = "";
        //Todo 表名，不要拼接，例：shiti
        String tableName = "";
        //Todo sessionId
        String phpSessionId = CookieUtil.getValue(request, "PHPSESSID");

        String downloadFileUrl = "";
        try {
            downloadFileUrl = uploadAndDownloadFileService.getDownloadFileUrl(defaultWebProtocol, defaultWebDomain, fileNameFromDB, recordId, fieldName, tableName, phpSessionId);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return downloadFileUrl;
        }
        if (StringUtils.isNotBlank(downloadFileUrl)) {
            return downloadFileUrl;
        } else {
            logger.error("getDownloadFileUrl error");
            return downloadFileUrl;
        }
    }

}
